<!--From表单种文件或者图片上传组件-->
<template>
  <div class="upload-file">
    <el-upload
      multiple
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :limit="limit"
      :action="uploadFileUrl"
      :headers="headers"

      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :list-type="type=='file'?'text':'picture-card'"
      :show-file-list="type!='file'"
      :disabled="readonly"
      :class="{hide: this.fileList.length >= this.limit||this.readonly}"
    >
      <!--    -->
      <el-button size="mini" type="primary" v-if="type=='file'">
        <span style="color: red;font-size: 12px;padding-right: 5px;" v-if="required">*</span>选取文件
      </el-button>
      <i class="el-icon-plus" v-else></i>
    </el-upload>
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b></template>
      的文件
    </div>
    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul" v-if="type=='file'">
      <li :key="file.filePath" class="el-upload-list__item ele-upload-list__item-content"
          v-for="(file, index) in fileList">
        <el-link type="primary" :underline="false">
          <span class="el-icon-document"> {{ file.fileName }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" v-if="!readonly" type="danger">删除</el-link>
          <el-link :underline="false" @click="handleDownload(file)" v-if="readonly" type="primary ">下载</el-link>
        </div>
      </li>
    </transition-group>

    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="800"
      append-to-body>
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script>
  import {getToken} from '@/utils/auth'
  import {listFileInfo} from "@/api/system/fileInfo"

  export default {
    name: 'FormFileUpload',
    props: {
      type: {
        type: String,
        default: "file"//img,file"
      },
      fileType: {    // 文件类型, 例如['png', 'jpg', 'jpeg']
        type: Array,
        default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf', 'png']
      },
      isShowTip: {
        type: Boolean,
        default: true,
      },
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 1024,
      },
      limit: {
        type: Number,
        default: 3
      },
      readonly: {
        type: Boolean,
        default: false
      },
      businessId: {//业务ID
        type: Number,
      },
      businessType: {//业务类型
        type: String,
        require: true
      },
      childType: {//业务子类型
        type: String,
      },
      required: {//业务类型
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        number: 0,
        uploadList: [],
        dialogImageUrl: '',//预览的图片地址
        dialogVisible: false,
        hideUpload: false,
        baseUrl: process.env.VUE_APP_BASE_API,
        uploadFileUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的文件服务器地址
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        fileList: []
      }
    },
    watch: {
      businessId: {
        handler(val) {
          this.iniListFileInfo();
        }
      }
    },
    computed: {
      // 是否显示提示
      showTip() {
        return this.isShowTip && (this.fileType || this.fileSize)
      }
    },
    mounted() {
      this.iniListFileInfo()
    },
    methods: {
      handleUploadSuccess(res) {  // 上传成功回调
        console.log("handleUploadSuccess", res)
        this.uploadList.push({
          fileName: res.originalFilename,
          filePath: res.fileName,
          url: this.baseUrl + res.fileName
        })
        if (this.uploadList.length === this.number) {
          this.fileList = this.fileList.concat(this.uploadList)
          this.uploadList = []
          this.number = 0
          this.$modal.closeLoading()
          this.$emit("change", this.fileList)
        }
      },
      handleBeforeUpload(file) {  // 上传前loading加载
        let isImg = false
        if (this.fileType.length) {
          let fileExtension = ''
          if (file.name.lastIndexOf('.') > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
          }
          isImg = this.fileType.some(type => {
            if (file.type.indexOf(type) > -1) return true
            if (fileExtension && fileExtension.indexOf(type) > -1) return true
            return false
          })
        } else {
          isImg = file.type.indexOf('image') > -1
        }
        if (!isImg) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join('/')}文件格式文件!`)
          return false
        }
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize
          if (!isLt) {
            this.$modal.msgError(`上传头像文件大小不能超过 ${this.fileSize} MB!`)
            return false
          }
        }
        this.$modal.loading('正在上传文件，请稍候...')
        this.number++
      },
      handleExceed() { // 文件个数超出
        this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`)
      },
      handleRemove(file) {// 删除文件
        console.log("handleRemove", file)
        if (this.type == 'file') {
          return
        }
        const findex = this.fileList.map(f => f.filePath).indexOf(file.filePath)
        this.handleDelete(findex)
      },
      handleDelete(index) {  // 删除文件
        this.fileList.splice(index, 1)
        this.$emit("change", this.fileList)
      },
      handleUploadError() {  // 上传失败
        this.$modal.msgError('上传文件失败，请重试')
        this.$modal.closeLoading()
      },
      handleDownload(row) { // 文件下载处理
        var name = row.fileName;
        var url = this.baseUrl + row.filePath;
        var suffix = url.substring(url.lastIndexOf("."), url.length);
        const a = document.createElement('a')
        a.setAttribute('download', name + suffix)
        a.setAttribute('target', '_blank')
        a.setAttribute('href', url)
        a.click()
      },
      handlePictureCardPreview(file) {//图片进行预览
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      //添加部分
      iniListFileInfo() { //初始化获取附件列表
        this.fileList = []
        if (!this.businessType || !this.businessId) {
          this.uploadList = [];
          this.number = 0;
          this.fileList = [];
          return
        }
        let filePara = {
          pageSize: 100000,
          businessType: this.businessType,
          businessId: this.businessId,
          childType: this.childType
        };
        listFileInfo(filePara)
          .then(res => {
            for (let item of res.rows) {
              this.fileList.push({
                ...item,
                url: this.baseUrl + item.filePath
              })
            }
          })
      },
      getFileList() { //获取上传文件的信息，用于外部调用
        return this.fileList
      },
      clearFileList() { //清空文件
        this.fileList = []
      },
    }
  }
</script>

<style scoped lang="scss">
  .upload-file-uploader {
    margin-bottom: 5px;
  }

  .upload-file-list .el-upload-list__item {
    border: 1px solid #e4e7ed;
    line-height: 2;
    margin-bottom: 10px;
    position: relative;
  }

  .upload-file-list .ele-upload-list__item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: inherit;
  }

  .ele-upload-list__item-content-action .el-link {
    margin-right: 10px;
  }
</style>
